package com.cj.ctyl.framework.exception;

import com.cj.ctyl.framework.core.Result;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Alex
 * @Description: 统一异常处理
 * @Date: 2021/8/15
 */
@RestControllerAdvice
public class CommonException {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Result handleException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String msg = String.format("访问的URL[%s]不支持%s请求", requestURI, e.getMethod());
        return Result.error(msg);
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result notFount(RuntimeException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        String msg = String.format("访问的URL[%s]发生异常%s", requestURI, e.getMessage());
        return Result.error(msg);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e)
    {
        return Result.error("服务器错误，请联系管理员");
    }

}
